package com.iot08.common.utils;

import java.security.MessageDigest;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 1/12/22 6:25 PM
 */
public class SignUtil {
    /**
     * MAC算法可选以下多种算法
     *
     * <pre>
     * HmacMD5
     * HmacSHA1
     * HmacSHA256
     * HmacSHA384
     * HmacSHA512
     * </pre>
     */
    public static final String HmacMD5 = "HmacMD5";
    public static final String HmacSHA1 = "HmacSHA1";
    public static final String HmacSHA256 = "HmacSHA256";
    public static final String HmacSHA384 = "HmacSHA384";
    public static final String HmacSHA512 = "HmacSHA512";


    /**
     * HMAC加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptHMAC(byte[] data, String key, String encryptType) throws Exception {

        SecretKey secretKey = new SecretKeySpec(key.getBytes(), encryptType);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);

        return mac.doFinal(data);

    }

    /*byte数组转换为HexString*/
    public static String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }

    public static void main(String[] args)throws Exception{
        String inputStr = "4f4bd39d9a52129e16357305301641957850";
        byte[] inputData = inputStr.getBytes();
        String key = "e4a7719cae83a3e7cc3a75dbd2dbda5e";
        System.out.println(SignUtil.byteArrayToHexString(SignUtil.encryptHMAC(inputData, key, SignUtil.HmacMD5)));
        System.out.println(String.format("%.02fM",2441849/1000.0/1024));
    }
}


